package com.postracker.postracker.db;

import java.sql.SQLException;

public class InsertRow {

	private static final String QUOTE = "'";

	private String sortedColumns[];
	private String sortedValues[];
	private String tableName;

	public InsertRow(String tableName, String[] sortedColumns)
			throws SQLException {
		this.tableName = tableName;
		this.sortedColumns = sortedColumns;
	}

	public void setSortedValues(String[] values) {
		this.sortedValues = values;
		prepareValuesToSql();
	}

	public String getInsertStatement() throws SQLException {
		StringBuilder sb = new StringBuilder();
		sb.append("insert into ").append(tableName).append(" (");
		sb = addCommaSeparatedValues(sortedColumns, sb);
		sb.append(") values( ");
		sb = addCommaSeparatedValues(sortedValues, sb);
		sb.append(")");
		return sb.toString();
	}

	private void prepareValuesToSql() {
		for (int i = 0; i < sortedColumns.length; i++) {
			sortedValues[i] = addQuotesIfRequired(sortedColumns[i],
					sortedValues[i]);
		}
	}

	private StringBuilder addCommaSeparatedValues(String[] values,
			StringBuilder sb) {
		final String separator = ", ";
		for (String value : values) {
			sb.append(value).append(separator);
		}
		return removeLastOcurrence(separator, sb);
	}

	private StringBuilder removeLastOcurrence(String occurrence,
			StringBuilder sb) {
		sb.delete(sb.lastIndexOf(", "), sb.length());
		return sb;
	}

	private String addQuotesIfRequired(String columnName, String value) {
		if (containsOnlyNumbers(value)) {
			return value;

		}
		StringBuilder sb = new StringBuilder(QUOTE);
		sb.append(value).append(QUOTE);
		return sb.toString();
	}

	private boolean containsOnlyNumbers(String string) {
		return string.matches("\\d+");
	}

}
